package com.moyun.syssecurity.sms.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.moyun.common.annotation.OperLog;
import com.moyun.model.common.R;
import com.moyun.common.validation.SMSCodeGroup;
import com.moyun.model.po.system.SysUserEntity;
import com.moyun.service.system.SysUserService;
import com.moyun.syssecurity.sms.pojo.SMSVO;
import com.moyun.syssecurity.sms.service.SendSms;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * <h3>org</h3>
 * <p>短信控制层</p>
 *
 * @author : ybx
 * @date : 2021-06-22 17:00:53
 **/
@RestController
@RequestMapping("/sms")
@Api(tags = "Authentication(系统认证)")
@RequiredArgsConstructor
public class SmsController {
    private final SendSms sendSms;
    private final SysUserService sysUserService;
    private final StringRedisTemplate stringRedisTemplate;

    @PostMapping("get-code")
    @ApiOperation(value = "短信验证码")
    @OperLog(operModul = "短信模块",operDesc = "获取短信验证码")
    public R<?> sendSms(@RequestBody @Validated({SMSCodeGroup.class}) SMSVO smsvo) throws Exception {
        //1. 验证数据库中是否存在该手机号(是否存在该用户)
        if (sysUserService.getOne(new QueryWrapper<SysUserEntity>().eq("phone",smsvo.getPhone()))==null) {
            return R.error("请先进行注册");
        }
        //2. 查一下redis中有无存放验证码 String.valueOf() 会出现 "null"的情况
        String code = this.stringRedisTemplate.opsForValue().get(smsvo.getPhone());
        // redisUtil 现在还不成熟
        //        Object o = redisUtil.get(smsvo.getPhone());
        //3. Redis缓存中的smsCode验证码未过期则不重新发送验证码
        if (!StringUtils.isEmpty(code)) {
            return R.error("上一个验证码还在有效期");
        } else {
            //调用方法发送验证码 传入电话
            boolean isSend = sendSms.addSendSms(smsvo.getPhone());
            if (isSend) {
                return R.ok("发送成功");
            } else {
                return R.error("发送失败");
            }
        }
    }
}